package com.fastCms.business.frame.plugins.email;

import com.fastCms.business.frame.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.internet.MimeMessage;
import java.text.MessageFormat;

/**
 * spring:
 * mail:
 * from: 316659431@qq.com
 * host: smtp.qq.com
 * password: xxxxxx
 * port: 25
 * properties:
 * mail:
 * smtp:
 * auth: true
 * socketFactory:
 * class: javax.net.ssl.SSLSocketFactory
 * starttls:
 * enable: true
 * required: true
 * username: 316659431@qq.com
 */

/**
 * spring:
 * mail:
 * from: aquan@indexed.cn
 * host: smtp.saas.huaweicloud.com
 * password:
 * port: 25
 * properties:
 * mail:
 * smtp:
 * auth: true
 * socketFactory:
 * class: javax.net.ssl.SSLSocketFactory
 * starttls:
 * enable: true
 * required: true
 * username: aquan@indexed.cn
 */

//qq发件服务器:smtp.qq.com,
//华为云服务器:smtp.saas.huaweicloud.com 默认端口25   启用ssl加密为465
@Slf4j
public class EmailUtil {

    private EmailProperties mailProperties;

    public EmailUtil(EmailProperties mailProperties) {
        this.mailProperties = mailProperties;
    }

    public void sendMail(String email, String yzm, Integer expireMinute) throws BusinessException {
        try {
            MimeMessage mimeMessage = mailProperties.getMailSender().createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(mailProperties.getCompanyName() + '<' + mailProperties.getEmailFrom() + '>');
            helper.setTo(email);
            helper.setSubject(mailProperties.getCompanyName());
            helper.setText(loadEmailJobAlarmTemplate(yzm, expireMinute), true);
            mailProperties.getMailSender().send(mimeMessage);
        } catch (Exception e) {
            log.error(">> sendMail fail:{}", e);
            throw new BusinessException("邮箱发送失败");
        }
    }

    private static final String loadEmailJobAlarmTemplate(String yzm, Integer expireMinute) {
        String mailBodyTemplate = "<!DOCTYPE html>\n" +
            "<html xmlns:th=\"http://www.thymeleaf.org\">\n" +
            "<head>\n" +
            "    <meta charset=\"utf-8\">\n" +
            "    <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n" +
            "    <meta name=\"description\" content=\"email code\">\n" +
            "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n" +
            "</head>\n" +
            "<!--邮箱验证码模板-->\n" +
            "<body>\n" +
            "<div style=\"background-color:#ECECEC; padding: 35px;\">\n" +
            "    <table cellpadding=\"0\" align=\"center\"\n" +
            "           style=\"width: 800px;height: 100%; margin: 0px auto; text-align: left; position: relative; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; font-size: 14px; font-family:微软雅黑, 黑体; line-height: 1.5; box-shadow: rgb(153, 153, 153) 0px 0px 5px; border-collapse: collapse; background-position: initial initial; background-repeat: initial initial;background:#fff;\">\n" +
            "        <tbody>\n" +
            "        <tr>\n" +
            "            <th valign=\"middle\"\n" +
            "                style=\"height: 25px; line-height: 25px; padding: 15px 35px; border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: RGB(148,0,211); background-color: RGB(148,0,211); border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 0px; border-bottom-left-radius: 0px;\">\n" +
            "                <font face=\"微软雅黑\" size=\"5\" style=\"color: rgb(255, 255, 255); \">安全中心消息</font>\n" +
            "            </th>\n" +
            "        </tr>\n" +
            "        <tr>\n" +
            "            <td style=\"word-break:break-all\">\n" +
            "                <div style=\"padding:25px 35px 40px; background-color:#fff;opacity:0.8;\">\n" +
            "\n" +
            "                    <h2 style=\"margin: 5px 0px; \">\n" +
            "                        <font color=\"#333333\" style=\"line-height: 20px; \">\n" +
            "                            <font style=\"line-height: 22px; \" size=\"4\">\n" +
            "                                尊敬的用户：</font>\n" +
            "                        </font>\n" +
            "                    </h2>\n" +
            "                    <!-- 中文 -->\n" +
            "                    <p>您好！感谢您使用我们的服务，您的账号正在进行邮箱验证，验证码为：<font color=\"#ff8c00\">{0}</font>，有效期" + expireMinute + "分钟，请尽快填写验证码完成验证！</p><br>\n" +
            "                    <div style=\"width:100%;margin:0 auto;\">\n" +
            "                        <div style=\"padding:10px 10px 0;border-top:1px solid #ccc;color:#747474;margin-bottom:20px;line-height:1.3em;font-size:12px;\">\n" +
            "                            <p>安全中心团队</p>\n" +
//                "                            <p>联系我们：aquan@indexed.cn</p>\n" +
            "                            <br>\n" +
            "                            <p>此为系统邮件，请勿回复<br>\n" +
            "                                Please do not reply to this system email\n" +
            "                            </p>\n" +
            "                            <!--<p>©***</p>-->\n" +
            "                        </div>\n" +
            "                    </div>\n" +
            "                </div>\n" +
            "            </td>\n" +
            "        </tr>\n" +
            "        </tbody>\n" +
            "    </table>\n" +
            "</div>\n" +
            "</body>\n" +
            "</html>\n";
        String htmlText = MessageFormat.format(mailBodyTemplate, yzm);

        return htmlText;
    }

//   398                         "<P><SPAN style=\"FONT-SIZE: 18px; FONT-WEIGHT: bold; COLOR: #f90\">"+code+"</SPAN><SPAN style=\"COLOR: #000000\">(为了保障您帐号的安全性，请在10分钟内完成验证)</SPAN></P>\n" +
//    public void sendMail(List<String> toUsers, String subject, String text) throws Exception{
//        //初始化默认参数
//        Properties props = new Properties();
//        props.setProperty("mail.transport.protocol", mailProperties.getTransportType());
//        props.setProperty("mail.host", mailProperties.getEmailHost());
//        props.setProperty("mail.user", mailProperties.getFromUser());
//        props.setProperty("mail.from", mailProperties.getFromEmail());
//        //获取Session对象
//        Session session = Session.getInstance(props, null);
//        //开启后有调试信息
//        //session.setDebug(true);
//
//        //通过MimeMessage来创建Message接口的子类
//        MimeMessage message = new MimeMessage(session);
//        //下面是对邮件的基本设置
//        //设置发件人：
//        //设置发件人第一种方式：直接显示：antladdie <antladdie@163.com>
//        //InternetAddress from = new InternetAddress(sender_username);
//        //设置发件人第二种方式：发件人信息拼接显示：蚂蚁小哥 <antladdie@163.com>
//        String formName = MimeUtility.encodeWord(mailProperties.getFromUser() + " <" + mailProperties.getFromEmail() + ">");
//        InternetAddress from = new InternetAddress(formName);
//        message.setFrom(from);
//
//        /*//设置收件人：
//        InternetAddress to = new InternetAddress(toEmail);
//        message.setRecipient(Message.RecipientType.TO, to);*/
//
//        List<InternetAddress> addresses = new ArrayList<>();
//        for(String toUser : toUsers){
//            InternetAddress to = new InternetAddress(toUser);
//            addresses.add(to);
//        }
//        //设置抄送人(两个)可有可无抄送人：
//        InternetAddress[] addressesArr = (InternetAddress[]) addresses.toArray();
//        message.setRecipients(Message.RecipientType.CC, addressesArr);
//
//        //设置密送人 可有可无密送人：
//        //InternetAddress toBCC = new InternetAddress(toEmail);
//        //message.setRecipient(Message.RecipientType.BCC, toBCC);
//
//        //设置邮件主题
//        message.setSubject(subject);
//
//        //设置邮件内容,这里我使用html格式，其实也可以使用纯文本；纯文本"text/plain"
//        message.setContent(text, "text/html;charset=UTF-8");
//
//        //保存上面设置的邮件内容
//        message.saveChanges();
//
//        //获取Transport对象
//        Transport transport = session.getTransport();
//        //smtp验证，就是你用来发邮件的邮箱用户名密码（若在之前的properties中指定默认值，这里可以不用再次设置）
//        //transport.connect(null, null, authCode);
//        //发送邮件
//        transport.sendMessage(message, message.getAllRecipients()); // 发送
//    }
}
